# -*- coding: utf-8 -*-
from flask import Blueprint,request,jsonify
# noinspection PyUnresolvedReferences
from common.libs.Helper import ops_render
# noinspection PyUnresolvedReferences
from application import  app
# noinspection PyUnresolvedReferences
from common.libs.Helper import getFormatDate,iPagination,getDictFilterField,selectFilterObj
# noinspection PyUnresolvedReferences
from common.models.stat.StatDailySite import StatDailySite
# noinspection PyUnresolvedReferences
from common.models.stat.StatDailyFood import StatDailyFood
# noinspection PyUnresolvedReferences
from common.models.stat.StatDailyMember import StatDailyMember
# noinspection PyUnresolvedReferences
from common.models.member.Member import Member
# noinspection PyUnresolvedReferences
from common.models.food.Food import Food
# noinspection PyUnresolvedReferences
from common.libs.stat.StatService import StatService
import datetime

route_stat = Blueprint( 'stat_page',__name__ )

@route_stat.route( "/index" )
def index():
    now = datetime.datetime.now()
    # 设置为本月第一天到今天
    first_day_of_month = now.replace(day=1)
    default_date_from = getFormatDate(date=first_day_of_month, format="%Y-%m-%d")
    default_date_to = getFormatDate(date=now, format="%Y-%m-%d")

    resp_data = {}
    req = request.values
    page = int(req['p']) if ('p' in req and req['p']) else 1
    date_from = req['date_from'] if 'date_from' in req else default_date_from
    date_to = req['date_to'] if 'date_to' in req else default_date_to
    # 将字符串日期转换为date对象进行比较
    date_from_obj = datetime.datetime.strptime(date_from, "%Y-%m-%d").date()
    date_to_obj = datetime.datetime.strptime(date_to, "%Y-%m-%d").date()
    query = StatDailySite.query.filter(StatDailySite.date >= date_from_obj) \
        .filter(StatDailySite.date <= date_to_obj)

    page_params = {
        'total': query.count(),
        'page_size': app.config['PAGE_SIZE'],
        'page': page,
        'display': app.config['PAGE_DISPLAY'],
        'url': request.full_path.replace("&p={}".format(page), "")
    }

    pages = iPagination(page_params)
    offset = (page - 1) * app.config['PAGE_SIZE']

    list = query.order_by(StatDailySite.date.desc(), StatDailySite.id.desc()).offset( offset ).limit( app.config['PAGE_SIZE'] ).all()
    resp_data['list'] = list
    resp_data['pages'] = pages
    resp_data['current'] = 'index'
    resp_data['search_con'] = {
        'date_from':date_from,
        'date_to':date_to
    }
    return ops_render( "stat/index.html",resp_data )

@route_stat.route( "/food" )
def food():
    now = datetime.datetime.now()
    # 设置为本月第一天到今天
    first_day_of_month = now.replace(day=1)
    default_date_from = getFormatDate(date=first_day_of_month, format="%Y-%m-%d")
    default_date_to = getFormatDate(date=now, format="%Y-%m-%d")

    resp_data = {}
    req = request.values
    page = int(req['p']) if ('p' in req and req['p']) else 1
    date_from = req['date_from'] if 'date_from' in req else default_date_from
    date_to = req['date_to'] if 'date_to' in req else default_date_to
    # 将字符串日期转换为date对象进行比较
    date_from_obj = datetime.datetime.strptime(date_from, "%Y-%m-%d").date()
    date_to_obj = datetime.datetime.strptime(date_to, "%Y-%m-%d").date()
    query = StatDailyFood.query.filter(StatDailyFood.date >= date_from_obj) \
        .filter(StatDailyFood.date <= date_to_obj)

    page_params = {
        'total': query.count(),
        'page_size': app.config['PAGE_SIZE'],
        'page': page,
        'display': app.config['PAGE_DISPLAY'],
        'url': request.full_path.replace("&p={}".format(page), "")
    }

    pages = iPagination(page_params)
    offset = (page - 1) * app.config['PAGE_SIZE']

    list = query.order_by(StatDailyFood.date.desc(), StatDailyFood.id.desc()).offset(offset).limit(app.config['PAGE_SIZE']).all()
    date_list = []
    if list:
        food_map = getDictFilterField(Food, Food.id, "id", selectFilterObj(list, "food_id"))
        for item in list:
            tmp_food_info = food_map[item.food_id] if item.food_id in food_map else {}
            tmp_data = {
                "date": item.date,
                "total_count": item.total_count,
                "total_pay_money": item.total_pay_money,
                'food_info': tmp_food_info
            }
            date_list.append(tmp_data)

    resp_data['list'] = date_list
    resp_data['pages'] = pages
    resp_data['current'] = 'food'
    resp_data['search_con'] = {
        'date_from': date_from,
        'date_to': date_to
    }
    return ops_render( "stat/food.html",resp_data  )

@route_stat.route( "/member" )
def member():
    now = datetime.datetime.now()
    # 设置为本月第一天到今天
    first_day_of_month = now.replace(day=1)
    default_date_from = getFormatDate(date=first_day_of_month, format="%Y-%m-%d")
    default_date_to = getFormatDate(date=now, format="%Y-%m-%d")

    resp_data = {}
    req = request.values
    page = int(req['p']) if ('p' in req and req['p']) else 1
    date_from = req['date_from'] if 'date_from' in req else default_date_from
    date_to = req['date_to'] if 'date_to' in req else default_date_to
    # 将字符串日期转换为date对象进行比较
    date_from_obj = datetime.datetime.strptime(date_from, "%Y-%m-%d").date()
    date_to_obj = datetime.datetime.strptime(date_to, "%Y-%m-%d").date()
    query = StatDailyMember.query.filter(StatDailyMember.date >= date_from_obj) \
        .filter(StatDailyMember.date <= date_to_obj)

    page_params = {
        'total': query.count(),
        'page_size': app.config['PAGE_SIZE'],
        'page': page,
        'display': app.config['PAGE_DISPLAY'],
        'url': request.full_path.replace("&p={}".format(page), "")
    }

    pages = iPagination(page_params)
    offset = (page - 1) * app.config['PAGE_SIZE']

    list = query.order_by(StatDailyMember.date.desc(), StatDailyMember.id.desc()).offset(offset).limit(app.config['PAGE_SIZE']).all()
    date_list = []
    if list:
        member_map = getDictFilterField( Member,Member.id,"id",selectFilterObj( list ,"member_id") )
        for item in list:
            tmp_member_info = member_map[ item.member_id ] if item.member_id in member_map else {}
            tmp_data = {
                "date":item.date,
                "total_pay_money":item.total_pay_money,
                "total_shared_count":item.total_shared_count,
                'member_info':tmp_member_info
            }
            date_list.append( tmp_data )

    resp_data['list'] = date_list
    resp_data['pages'] = pages
    resp_data['current'] = 'member'
    resp_data['search_con'] = {
        'date_from': date_from,
        'date_to': date_to
    }
    return ops_render( "stat/member.html",resp_data  )

@route_stat.route( "/share" )
def share():
    now = datetime.datetime.now()
    # 设置为本月第一天到今天
    first_day_of_month = now.replace(day=1)
    default_date_from = getFormatDate(date=first_day_of_month, format="%Y-%m-%d")
    default_date_to = getFormatDate(date=now, format="%Y-%m-%d")

    resp_data = {}
    req = request.values
    page = int(req['p']) if ('p' in req and req['p']) else 1
    date_from = req['date_from'] if 'date_from' in req else default_date_from
    date_to = req['date_to'] if 'date_to' in req else default_date_to
    # 将字符串日期转换为date对象进行比较
    date_from_obj = datetime.datetime.strptime(date_from, "%Y-%m-%d").date()
    date_to_obj = datetime.datetime.strptime(date_to, "%Y-%m-%d").date()
    query = StatDailySite.query.filter(StatDailySite.date >= date_from_obj) \
        .filter(StatDailySite.date <= date_to_obj)

    page_params = {
        'total': query.count(),
        'page_size': app.config['PAGE_SIZE'],
        'page': page,
        'display': app.config['PAGE_DISPLAY'],
        'url': request.full_path.replace("&p={}".format(page), "")
    }

    pages = iPagination(page_params)
    offset = (page - 1) * app.config['PAGE_SIZE']

    list = query.order_by(StatDailySite.date.desc(), StatDailySite.id.desc()).offset(offset).limit(app.config['PAGE_SIZE']).all()
    resp_data['list'] = list
    resp_data['pages'] = pages
    resp_data['current'] = 'food'
    resp_data['search_con'] = {
        'date_from': date_from,
        'date_to': date_to
    }
    return ops_render( "stat/share.html",resp_data  )

@route_stat.route("/update", methods=["POST"])
def updateStats():
    """手动更新统计数据"""
    resp = {'code': 200, 'msg': '统计数据更新成功~', 'data': {}}
    req = request.values
    date = req['date'] if 'date' in req else getFormatDate(format="%Y-%m-%d")
    
    try:
        stat_service = StatService()
        
        # 更新指定日期的统计数据
        # 这里可以添加更复杂的逻辑来更新特定日期的数据
        app.logger.info(f"开始手动更新 {date} 的统计数据")
        
        # 可以在这里添加批量更新逻辑
        resp['msg'] = f"{date} 的统计数据更新成功"
        
    except Exception as e:
        app.logger.error(f"手动更新统计数据失败: {str(e)}")
        resp['code'] = -1
        resp['msg'] = f"统计数据更新失败: {str(e)}"
    
    return jsonify(resp)
